// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#include <cantor/parser/parser.h>
#include <cantor/transform/dmls/assignment.h>
#include <cantor/transform/exprs/range_var.h>
#include <cantor/transform/expr.h>

#include "cantor/transform/clause/column_name.h"

namespace cantor::transform {

    void TransAssignment::resolve_ast(const cantor::parser::Assignment*node) {
        if (!node) {
            status = turbo::data_loss_error("no expr");
            return;
        }
        if (!node->name) {
            make_missing_required_field("name");
            return;
        }
        if (!node->expr) {
            make_missing_required_field("expr");
            return;
        }

        status = TransExpr::resolve_to(node->expr, assignment.mutable_expr());
        if (!status.ok()) {
            return;
        }

        status = TransColumnName::resolve_to(node->name, assignment.mutable_name());
        set_proto_location(node, assignment.mutable_location());
        set_proto_status(assignment.mutable_status());
    }

    const turbo::Status &TransAssignment::check() {
        if (!status.ok()) {
            return status;
        }
        if (!assignment.has_location()) {
            make_missing_required_field("location");
            return status;
        }
        if (!assignment.has_expr()) {
            make_missing_required_field("expr");
            return status;
        }
        if (!assignment.has_name()) {
            make_missing_required_field("name");
        }
        return status;
    }

    turbo::Status TransAssignment::resolve_to(turbo::Nonnull<const cantor::parser::Assignment*> arg, turbo::Nonnull<pb::ast::Assignment *>out) {
        TransAssignment trans;
        trans.resolve_ast(arg);
        auto status = trans.check();
        if (!status.ok()) {
            return status;
        }
        *out = std::move(trans.assignment);
        return status;
    }
}  // namespace cantor::transform
